/**
 * 收费模式编辑框
 */
import React, { Component } from 'react';
import { Button, message, Select } from 'antd';
import cass from 'classnames';
import { thirdAdd, thirdUpdate, thirdQuery, thirdDel } from '../../../services/product';
import { isSuccess } from '../../../configs/error';
import css from '../../../themes/index.less';
import ThirdConfigurationItem, { defaultValue } from './thirdConfigurationItem';

const Option = Select.Option;

const styles = {
  main: {
    display: 'block',
    padding: '0',
    lineHeight: '2'
  },
  b: {
    float: 'right'
  },
  title: {
    fontSize: '18px'
  },
};

class ThirdConfigurationBox extends Component {
  state = {
    data: [],
		params: [],
		vendors: []
  }

  async componentWillMount() {
    const { productId } = this.props;
    if (productId) {
      // 获取当前产品的收费模式
      // const res = await productCommandQuery({ productId });
      const res = await thirdQuery({ productId });
      if (isSuccess(res)) {
        this.setState({
					data: res.data.items,
					...res.data
        });
      }
    }
  }

  add = () => {
    // 添加
    const { data } = this.state;
    this.setState({
      data: [{ ...defaultValue }].concat(data)
    });
  }

  save = async data => {
    const newCommand = {
      ...data,
      productId: this.props.productId,
    };
    let res = null;
    if (data.id) {
      // 修改
      newCommand.id = data.id;
      delete newCommand.commandType;
      res = await thirdUpdate(newCommand);
    } else {
			// 新增
      res = await thirdAdd(newCommand);
    }
    if (isSuccess(res)) this.componentWillMount();
  }

  delete = async id => {
    // 删除
    const { data } = this.state;
    const res = await thirdDel({ ids: [id] });
    if (isSuccess(res)) {
      message.success('删除成功');
      this.setState({ data: data.filter(d => d.id !== id) });
    }
  }

  cancel = index => {
    const { data } = this.state;
    this.setState({
      data: data.filter((d, i) => i !== index)
    });
  }

  render() {
    const { data, params, vendors } = this.state;
    const { show, dataPoint, productId } = this.props;
    styles.main.display = show ? 'block' : 'none';
    return (
      <div style={styles.main}>
        <div className={cass(css.layout, css.lr)}>
          <div>设置上报指令</div>
          <div className={css.right}>
            <Button style={styles.b} onClick={this.add} icon="plus" className="opt-but">添加</Button>
          </div>
        </div>
        <div style={styles.box}>
          {data.map((d, i) => (
            <ThirdConfigurationItem
              key={d.id}
              index={i}
              dataPoint={dataPoint}
              productId={productId}
              data={d}
              save={this.save}
              delete={this.delete}
							cancel={this.cancel}
							params={params}
							vendors={vendors}
            />
          ))}
        </div>
      </div>
    );
  }
}

ThirdConfigurationBox.propTypes = {

};

export default ThirdConfigurationBox;
